package com.edu.hre.struts.action.survey;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.derby.iapi.sql.dictionary.ConsInfo;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.util.LabelValueBean;

import com.edu.hre.common.cache.PassiveDynaCache;
import com.edu.hre.common.runable.NotifyEMailSurvey;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.Constants;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.db.pojo.HreSurveyEmpAnswer;
import com.edu.hre.db.pojo.HreSurveyQuestion;
import com.edu.hre.db.pojo.HreSurveyQuestionAnswer;
import com.edu.hre.db.pojo.HreSurveyTopic;
import com.edu.hre.db.pojo.HreSubunit;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.dashboard.DashLeaveForm;
import com.edu.hre.struts.form.survey.SurveyManagementListForm;
import com.edu.hre.struts.form.survey.SurveyManagementUpdateForm;
import com.ibm.icu.util.Calendar;
import com.lowagie.tools.concat_pdf;

public class SurveyManagementUpdateAction extends DispatchAction {
	
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private static final PassiveDynaCache passiveDynaCache = BeanFinder.getBean(PassiveDynaCache.BEAN_NAME, PassiveDynaCache.class);
	
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonUtils.println(CommonUtils.getSourceCodeLocation()); 
		HreUser user = (HreUser) request.getSession().getAttribute(RequestUtils.Attribute.USER_INFO);
		SurveyManagementUpdateForm beanForm = (SurveyManagementUpdateForm) form;
		beanForm.setMethod("add");
		if(request.getParameter("btnAdd") == null){
			List<LabelValueBean> listTmp = CommonUtils.getSubunits();
			beanForm.setListSubunit(listTmp);
			beanForm.setSubunitId(Integer.parseInt(listTmp.get(0).getValue())); 
			beanForm.setStartDate(new Date());
			
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DATE, 7);
			beanForm.setEndDate(cal.getTime());
			
			return mapping.findForward("surveyUpdate");
		} else {
			String topicStr = request.getParameter("areaTopic");
			CommonUtils.println("Topic = " + topicStr);
			Date startDate = beanForm.getStartDate();
			CommonUtils.println("StartDate = " + startDate);
			Date endDate = beanForm.getEndDate();
			CommonUtils.println("EndDate = " + endDate);
			int subunitId = beanForm.getSubunitId();
			CommonUtils.println("SubunitId = " + subunitId);
			HreSurveyTopic topic = new HreSurveyTopic(topicStr, subunitId, startDate, endDate, user.getId(), new Date(), new Date(), beanForm.getShowToAll());
			baseService.save(topic);
			insertQuestionsAndAnswer(request, topic);
			try {
				NotifyEMailSurvey runable = new NotifyEMailSurvey(topic.getId(), topic.getSubunitId());
				Constants.executor.execute(runable);
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
		passiveDynaCache.removeIfKeyStartWith(RequestUtils.Attribute.TAKE_SURVEY_NOTIFICATION);
		return new ActionForward("/surveyList.do", true);
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		CommonUtils.println(CommonUtils.getSourceCodeLocation()); 
		HreUser user = (HreUser) request.getSession().getAttribute(RequestUtils.Attribute.USER_INFO);
		SurveyManagementUpdateForm beanForm = (SurveyManagementUpdateForm) form;
		if("true".equalsIgnoreCase(request.getParameter("clone"))){
			beanForm.setMethod("clone");
		} else {
			beanForm.setMethod("edit");
		}
		String id = request.getParameter("id");
		CommonUtils.println("Updating survey that ID = " + id);
		HreSurveyTopic topic = baseService.getPojo(Integer.parseInt(id), HreSurveyTopic.class);
		HreSurveyEmpAnswer userTaken = baseService.getFirstPojo("topicId", Compare.EQUAL, topic.getId(), HreSurveyEmpAnswer.class);
		if(userTaken != null && !"true".equalsIgnoreCase(request.getParameter("clone"))){
			response.getWriter().write("Can not edit this survey because someone have been taken it!");
			return null;
		}
		if(request.getParameter("btnUpdate") == null){ 
			beanForm.setAreaTopic(topic.getName());
			beanForm.setStartDate(topic.getStartDate());
			beanForm.setEndDate(topic.getEndDate());
			
			beanForm.setListSubunit(CommonUtils.getSubunits());
			beanForm.setSubunitId(topic.getSubunitId()); 
			
			String html = "";
			List<HreSurveyQuestion> listQuestion = baseService.getPojos("topicId", Compare.EQUAL, topic.getId(), new String[]{"rank"}, new Boolean[]{false}, 0, 0, HreSurveyQuestion.class);
			for(int i = 0; listQuestion != null && i < listQuestion.size(); i ++){
				HreSurveyQuestion question = listQuestion.get(i);
				int questionOrder = i + 1;
				String checkMulti = question.getType() == 1 ? "checked" : "";
				String checkSingle = question.getType() == 1 ? "" : "checked";
				html += "<div id=\"questionDiv" + questionOrder + "\">" + 
								"<br/><br/><br/><hr/>" +
								"<label><b>Question:</b></label>" + 
								"<textarea name=\"txtQuestion" + questionOrder + "\" style=\"width: 630px;\" id=\"txtQuestion"  + questionOrder + "\">" + question.getText() + "</textarea>" + 
								"<input id=\"btnRemoveQuestion" + questionOrder + "\" type=\"button\"  value=\"Remove\" onclick=\"removeQuestion(this);\"/>" + 
								"<br/><label></label>" + 
								"<input type=\"radio\" name=\"radio" + questionOrder + "\" value=\"multi\" " + checkMulti + ">Multiple response</input>" +
								"<input type=\"radio\" name=\"radio" + questionOrder + "\" value=\"single\" " + checkSingle + ">Multiple choice</input><br/>" +
								"<br/><label></label>";
				List<HreSurveyQuestionAnswer> listAnswer = baseService.getPojos("questionId", Compare.EQUAL, question.getId(), new String[]{"label"}, new Boolean[]{false}, 0, 0, HreSurveyQuestionAnswer.class);
				for(int k = 0; listAnswer != null && k < listAnswer.size(); k ++){
					HreSurveyQuestionAnswer answer = listAnswer.get(k);
					String nameAnswer = questionOrder + "_" + (k + 1);
					String checkedFreeText = answer.getType() == 2 ? "checked" : "";
					html += "<div id=\"answerDiv_" + nameAnswer + "\">";
					html +=  "<b>Answer:&nbsp;</b>" + 
							"<textarea name=\"txtAnswer_" + nameAnswer + "\" style=\"width: 350px;height: 25px\" id=\"txtAnswer_" + nameAnswer + "\">" + answer.getText() + "</textarea>" +
							"<input type=\"checkbox\" name=\"cbo_" + nameAnswer + "\" " + checkedFreeText + ">Allow Free Text</input>" +
							"&nbsp;&nbsp;&nbsp;<input id=\"answerDiv_" + nameAnswer + "\" type=\"button\" value=\"Remove\" onclick=\"removeAnswer(this);\"/>" + 
							"<br/><label></label>";
					html += "</div>";
				}
				html += "<input id=\"btnAddAnswer" + questionOrder + "\" type=\"button\"  value=\"Add answer\" onclick=\"addAnswer(this);\"/>";
				html += "</div>";
			}
			beanForm.setShowToAll(topic.getShowToAll());
			beanForm.setHtml(html);
			beanForm.setId(Integer.parseInt(id));
			return mapping.findForward("surveyUpdate");
		} else {
			if(!"true".equalsIgnoreCase(request.getParameter("clone"))){
				List<HreSurveyQuestion> listOldQuestion = baseService.getPojos("topicId", Compare.EQUAL, topic.getId(), null, null, 0, 0, HreSurveyQuestion.class);
				baseService.deletePojos(listOldQuestion);
			}
			
			String topicStr = request.getParameter("areaTopic");
			CommonUtils.println("Topic = " + topicStr);
			Date startDate = beanForm.getStartDate();
			CommonUtils.println("StartDate = " + startDate);
			Date endDate = beanForm.getEndDate();
			CommonUtils.println("EndDate = " + endDate);
			int subunitId = beanForm.getSubunitId();
			CommonUtils.println("SubunitId = " + subunitId);
			
			if("true".equalsIgnoreCase(request.getParameter("clone"))){
				topic = new HreSurveyTopic();
				topic.setDateCreated(new Date());
			}
			topic.setDateModified(new Date());
			topic.setName(topicStr);
			topic.setStartDate(startDate);
			topic.setEndDate(endDate);
			topic.setSubunitId(subunitId);
			topic.setUserCreated(user.getId());
			topic.setShowToAll(beanForm.getShowToAll());
			
			baseService.saveOrUpdate(topic); 
			insertQuestionsAndAnswer(request, topic);
			passiveDynaCache.removeIfKeyStartWith(RequestUtils.Attribute.TAKE_SURVEY_NOTIFICATION);
			try {
				if("true".equalsIgnoreCase(request.getParameter("clone"))){
					NotifyEMailSurvey runable = new NotifyEMailSurvey(topic.getId(), topic.getSubunitId());
					Constants.executor.execute(runable);
				}
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
			return new ActionForward("/surveyList.do", true);
		}
	}
	
	private boolean isValidQuestion(HttpServletRequest request, int i){
		String question = request.getParameter("txtQuestion" + i);
		if(StringUtils.isBlank(question)){
			return false;
		}
		int countAnswer = 0;
		for(int k = 0; k < 20; k++){
			String answer = request.getParameter("txtAnswer_" + i + "_" + k);
			if(answer != null){
				countAnswer ++;
			}
		}
		if(countAnswer < 1){
			return false;
		}
		return true;
	}
	 
	
	private void insertQuestionsAndAnswer(HttpServletRequest request, HreSurveyTopic topic){
		for(int i = 0; i < 700; i++){
			try {
				if(isValidQuestion(request, i)){
					String questionStr = request.getParameter("txtQuestion" + i);
					CommonUtils.println("===================================");
					CommonUtils.println("Loop " + i + ": " + questionStr);
					String typeStr = request.getParameter("radio" + i);
					CommonUtils.println(", Question type:" + typeStr);
					int questionType = "multi".equalsIgnoreCase(typeStr) ? 1 : 2;
					HreSurveyQuestion questionObj = new HreSurveyQuestion(questionStr, questionType, topic.getId(), new Date(), new Date(), i);
					baseService.save(questionObj);
					int labelIndex = 0;
					for(int k = 0; k < 50; k++){
						try {
							String answerStr = request.getParameter("txtAnswer_" + i + "_" + k);
							if(answerStr == null){
								continue;
							}
							CommonUtils.println("Answer " + k + ": " + answerStr);
							String freeText = request.getParameter("cbo_" +  + i + "_" + k);
							CommonUtils.println(", FreeText: " + freeText);
							int answerType = "on".equalsIgnoreCase(freeText) ? 2 : 1;
							HreSurveyQuestionAnswer answer = new HreSurveyQuestionAnswer(String.valueOf(Character.toChars(labelIndex + 65)), questionObj.getId(), answerType, answerStr);
							baseService.save(answer);
							labelIndex ++;
						} catch (Exception e) {
							CommonUtils.println(e.getMessage());
						}
					}
				}
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
	}
}
